/*
* This file is a part of the open-eBackup project.
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* Copyright (c) [2024] Huawei Technologies Co.,Ltd.
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*/
package com.huawei.emeistor.console.config.lock.impl;

/**
 * 保存锁的上下文，方便判断是否真的已获取锁
 *
 */
public class LockAssert {
    private static final ThreadLocal<String> CURRENT_LOCK_NAME = ThreadLocal.withInitial(() -> null);

    /**
     * 锁开始
     *
     * @param name 锁名称
     */
    static void startLock(String name) {
        CURRENT_LOCK_NAME.set(name);
    }

    /**
     * 是否已经被锁住
     *
     * @param name 锁名称
     * @return 是否已经被锁住
     */
    static boolean alreadyLockedBy(String name) {
        return name.equals(CURRENT_LOCK_NAME.get());
    }

    /**
     * 锁结束
     */
    static void endLock() {
        CURRENT_LOCK_NAME.remove();
    }

    /**
     * 断言当前线程已经获得锁
     */
    public static void assertLocked() {
        if (CURRENT_LOCK_NAME.get() == null) {
            throw new IllegalStateException("The task is not locked.");
        }
    }
}
